package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNameRole = "roles"

// Role mapped from table <roles>
type Role struct {
	ID          int64  `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id,string"`
	Name        string `gorm:"column:name;type:varchar(255)" json:"name"`
	Description string `gorm:"column:description;type:text" json:"description"`
}

// TableName Role's table name
func (*Role) TableName() string {
	return TableNameRole
}

// CreateRole creates a new Role in the database.
func (m *Role) CreateRole() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetRoleByID retrieves a Role by its ID from the database.
func (m *Role) GetRoleByID(id int64) (*Role, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // Role not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateRole updates an existing Role in the database.
func (m *Role) UpdateRole() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteRole deletes a Role by its ID from the database.
func (m *Role) DeleteRole(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}

// 获取权限列表 ,page limit
func (m *Role) GetRoleList(page, limit int) ([]*Role, error) {
	var roleList []*Role
	if err := global.Db.Limit(limit).Offset((page - 1) * limit).Find(&roleList).Error; err != nil {
		return nil, err
	}
	return roleList, nil
}
